package com.bridata.config;

import com.bridata.model.entity.ScreenPicture;
import com.bridata.service.ScreenPictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 屏幕图片定时任务调度器
 */
@Slf4j
@Component
public class ScreenPictureScheduler {

    @Autowired
    private ScreenPictureService screenPictureService;

    @Value("${scheduler.batch-size:2}")
    private Integer batchSize;

    private static Integer index = -1;

    private final ExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    /**
     * 主定时任务 - 每秒执行一次
     */
    @Scheduled(fixedRate = 1000)
    public void processMainTask() {
        try {
            index = index + 1;
            log.info("当前请求位置：{}", index);
            
            int offset = index * batchSize;
            log.info("当前请求数据起始：{}, 查询条数：{}", offset, batchSize);
            
            List<ScreenPicture> records = screenPictureService.fetchRecords(offset, batchSize);
            if (records.isEmpty()) {
                log.info("未找到待处理记录");
                index = -1;
                return;
            }
            
            screenPictureService.processRecordsAsync(records);
        } catch (Exception e) {
            log.error("主任务执行失败", e);
        }
    }


    /**
     * 应用关闭前优雅关闭线程池
     */
    @PreDestroy
    public void shutdownGracefully() {
        try {
            scheduler.shutdown();
            if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
            log.info("定时任务线程池关闭完成");
        } catch (Exception e) {
            log.error("关闭过程中发生异常", e);
        }
    }
}